package controllers;

import models.Bar;
import models.User;

import org.springframework.beans.factory.annotation.Autowired;

import play.data.Form;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import services.BarService;
import views.html.*;

@org.springframework.stereotype.Controller
public class Application extends Controller {

    @Autowired
    private BarService barService;

    public Result index() {
        return play.mvc.Controller.ok(index.render(Form.form(Bar.class)));
    }

    public Result indexSegurosMoran() {
        return ok(indexSegurosMoran.render("HOLA SEGUROS MORGAN"));
    }

    public Result addBar() {
        Form<Bar> form = Form.form(Bar.class).bindFromRequest();
        Bar bar = form.get();
        barService.addBar(bar);
        return play.mvc.Controller.redirect(controllers.routes.Application.index());
    }

    public Result listBars() {
        return play.mvc.Controller.ok(Json.toJson(barService.getAllBars()));
    }
 
	public Result login() {
		return ok(login.render(Form.form(Login.class)));
	}
    
	public Result authenticate() {
	    Form<Login> loginForm = Form.form(Login.class).bindFromRequest();
	    
	    if (loginForm.hasErrors()) {
	        return badRequest(login.render(loginForm));
	    } else {
	        session().clear();
	        session("email", loginForm.get().email);
	        return redirect(
	            routes.Application.indexSegurosMoran()
	        );
	    }
	}
	

	public static class Login {

	    public String email;
	    public String password;
	    
		public String validate() {
		    if (User.authenticate(email, password) == null) {
		      return "Invalid user or password";
		    }
		    return null;
		}
	}
}